package settings;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.imstlife.vending.R;
import com.imstlife.vending.adapter.MyListViewAdapter;
import com.imstlife.vending.utils.T;
import com.wifi.OnNetworkChangeListener;
import com.wifi.WifiAdmin;
import com.wifi.WifiConnDialog;
import com.wifi.WifiStatusDialog;

import java.util.ArrayList;
import java.util.List;

public class WiFiFragment extends Fragment {

    private static String TAG = "WiFiFragment";

    private static final int REFRESH_CONN = 100;

    private static final int REQ_SET_WIFI = 200;

    // WiFi管理类
    private WifiAdmin mWifiAdmin;
    // 扫描结果列表
    private List<ScanResult> list = new ArrayList<ScanResult>();
    // 显示列表
    private ListView listView;
    // private ToggleButton tgbWifiSwitch;

    private MyListViewAdapter mAdapter;

    private OnNetworkChangeListener mOnNetworkChangeListener = new OnNetworkChangeListener() {

        @Override
        public void onNetWorkDisConnect() {
            getWifiListInfo();
            mAdapter.setDatas(list);
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNetWorkConnect() {
            getWifiListInfo();
            mAdapter.setDatas(list);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mAdapter.notifyDataSetChanged();
        }
    };

    private TextView currentTextView;
    /**
     * 打开关闭提示
     */
    private TextView tipTextView;
    /**
     * 打开关闭开关
     */
    private Switch wifiSwitch;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootLayout = inflater.inflate(R.layout.fragment_wifi, container,
                false);

        currentTextView = (TextView) rootLayout
                .findViewById(R.id.fragment_wifi_current);
        tipTextView = (TextView) rootLayout
                .findViewById(R.id.fragment_wifi_tip);
        listView = (ListView) rootLayout.findViewById(R.id.fragment_wifi_list);

        wifiSwitch = (Switch) rootLayout
                .findViewById(R.id.fragment_wifi_switch);

        initData();

        mAdapter = new MyListViewAdapter(getActivity(), list);
        listView.setAdapter(mAdapter);
        //
        int wifiState = mWifiAdmin.checkState();
        if (wifiState == WifiManager.WIFI_STATE_DISABLED
                || wifiState == WifiManager.WIFI_STATE_DISABLING
                || wifiState == WifiManager.WIFI_STATE_UNKNOWN) {

            wifiSwitch.setChecked(false);

            tipTextView.setVisibility(View.VISIBLE);
            tipTextView.setText(R.string.please_open_wlan);
            listView.setVisibility(View.INVISIBLE);
        } else {
            wifiSwitch.setChecked(true);

            tipTextView.setVisibility(View.INVISIBLE);
            listView.setVisibility(View.VISIBLE);
        }

        setListener();

        refreshWifiStatusOnTime();

        return rootLayout;
    }

    private void initData() {
        mWifiAdmin = new WifiAdmin(getActivity());
        // 获得WiFi列表信息
        getWifiListInfo();
    }

    private void setListener() {

        wifiSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if (isChecked) {
                    Log.w(TAG, "======== open wifi ========");

                    tipTextView.setText(R.string.openning_wlan);
                    // 打开Wifi
                    mWifiAdmin.openWifi();
                } else {
                    Log.w(TAG, "======== close wifi ========");

                    tipTextView.setVisibility(View.VISIBLE);
                    tipTextView.setText(R.string.please_open_wlan);
                    listView.setVisibility(View.INVISIBLE);

                    mWifiAdmin.closeWifi();
                }
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // String wifiName = list.get(position).SSID;
                // String singlStrength = "" + list.get(position).frequency;
                // String secuString = list.get(position).capabilities;

                ScanResult scanResult = list.get(position);

                String desc = "";
                String descOri = scanResult.capabilities;
                if (descOri.toUpperCase().contains("WPA-PSK")) {
                    desc = "WPA";
                }
                if (descOri.toUpperCase().contains("WPA2-PSK")) {
                    desc = "WPA2";
                }
                if (descOri.toUpperCase().contains("WPA-PSK")
                        && descOri.toUpperCase().contains("WPA2-PSK")) {
                    desc = "WPA/WPA2";
                }

                if (desc.equals("")) {
                    isConnectSelf(scanResult);

                    return;
                }

                isConnect(scanResult);
            }

            private void isConnect(ScanResult scanResult) {
                if (mWifiAdmin.isConnect(scanResult)) {
                    // 已连接，显示连接状态对话框
                    WifiStatusDialog mStatusDialog = new WifiStatusDialog(
                            getActivity(), R.style.PopDialog, scanResult,
                            mOnNetworkChangeListener);
                    mStatusDialog.show();
                } else {
                    // 未连接显示连接输入对话框
                    WifiConnDialog mDialog = new WifiConnDialog(getActivity(),
                            R.style.PopDialog, scanResult,
                            mOnNetworkChangeListener);
                    // WifiConnDialog mDialog = new WifiConnDialog(
                    // WifiListActivity.this, R.style.PopDialog, wifiName,
                    // singlStrength, secuString);
                    mDialog.show();
                }
            }

            private void isConnectSelf(ScanResult scanResult) {
                if (mWifiAdmin.isConnect(scanResult)) {

                    // 已连接，显示连接状态对话框
                    WifiStatusDialog mStatusDialog = new WifiStatusDialog(
                            getActivity(), R.style.PopDialog, scanResult,
                            mOnNetworkChangeListener);
                    mStatusDialog.show();

                } else {
                    boolean iswifi = mWifiAdmin.connectSpecificAP(scanResult);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (iswifi) {

                        T.showShort(getActivity(), getResources().getString(
                                R.string.connection_success));
                    } else {
                        T.showShort(getActivity(), getResources().getString(
                                R.string.connection_failed));

                    }
                }
            }
        });
    }

    private void getWifiListInfo() {
        System.out.println("WifiListActivity#getWifiListInfo");

        mWifiAdmin.startScan();
        List<ScanResult> tmpList = mWifiAdmin.getWifiList();
        if (tmpList == null) {
            list.clear();
        } else {
            list = tmpList;

            tipTextView.setVisibility(View.INVISIBLE);
            listView.setVisibility(View.VISIBLE);
        }
    }

    private Handler mHandler = new MyHandler();

    protected boolean isUpdate = true;

    private class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case REFRESH_CONN:
                    getWifiListInfo();
                    mAdapter.setDatas(list);
                    mAdapter.notifyDataSetChanged();
                    break;

                default:
                    break;
            }

            super.handleMessage(msg);
        }

    }

    /**
     * Function:定时刷新Wifi列表信息<br>
     *
     * @author ZYT DateTime 2014-5-15 上午9:14:34<br>
     * <br>
     */
    private void refreshWifiStatusOnTime() {
        new Thread() {
            public void run() {
                while (isUpdate) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessage(REFRESH_CONN);
                }
            }
        }.start();
    }

    @Override
    public void onDestroyView() {
        isUpdate = false;

        super.onDestroyView();
    }

}
